import autoDisposeWhenUnload from "./autoDisposeWhenUnload";

const instanceList = [];
const dataList = [];

autoDisposeWhenUnload(function () {
    instanceList.forEach(i => i?.destroy());
    instanceList.splice(0, instanceList.length);
    dataList.splice(0, dataList.length);
});

export default class Queue {
    constructor() {
        instanceList.push(this);
        dataList.push([]);
    }

    get count() {
        return dataList[instanceList.indexOf(this)].length;
    }

    push(item) {
        dataList[instanceList.indexOf(this)].push(item);
        return this;
    }

    pop() {
        return dataList[instanceList.indexOf(this)].pop();
    }

    top() {
        return dataList[instanceList.indexOf(this)][this.count - 1];
    }

    isHas(item) {
        return dataList[instanceList.indexOf(this)].includes(item);
    }

    toArray() {
        return dataList[instanceList.indexOf(this)].slice();
    }

    destroy() {
        const index = instanceList.indexOf(this);
        instanceList[index] = null;
        dataList[index] = null;
    }
}
